package com.ddx.controller.core;


import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.ddx.common.exception.ExceptionUtil;
import com.ddx.common.exception.ResultModel;
import com.ddx.common.util.CommonUtils;
import com.ddx.dto.UserDto;
import com.ddx.pojo.User;
import com.ddx.pojo.UserFollow;
import com.ddx.service.IUserService;
import com.ddx.service.UserFollowService;

import io.swagger.annotations.ApiOperation;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lyxiang
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping(value = "/user")
public class UserController {

    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    IUserService iUserService;

    @Autowired
    UserFollowService userFollowService;

    /**
     * 退出登录
     *
     * @return
     */
    @RequestMapping(value = "/signOut", method = RequestMethod.POST)
    public ResultModel signOut(HttpServletRequest request) {
        String userId = request.getHeader("userId");
        iUserService.signOut(userId);
        return ResultModel.getSuccessInstance();
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
    public ResultModel getUserInfo(HttpServletRequest request) {
        ResultModel resultModel = ResultModel.getSuccessInstance();
        String userId = request.getHeader("userId");
        User user = iUserService.getUserInfo(userId);
        resultModel.setData(user);
        return resultModel;
    }

    /**
     * 保存用户信息
     *
     * @return
     */
    @RequestMapping(value = "/saveUserInfo", method = RequestMethod.POST)
    public ResultModel saveUserInfo(HttpServletRequest request, @RequestBody User user) {
        try {
            String userId = request.getHeader("userId");
            user.setId(Integer.parseInt(userId));
            iUserService.saveUserInfo(user);
            return ResultModel.getSuccessInstance();
        } catch (Exception e) {
            logger.error("getUserCenterInfo error", e);
            return ExceptionUtil.getMessageException(e);
        }
    }
    
    /**
     * 编辑用户资料
     */
    @ApiOperation(value = "编辑用户资料", notes = "")
    @CrossOrigin(origins = "*", maxAge = 3600)
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public ResultModel edit(HttpServletRequest request, @RequestBody User user) {
        ResultModel resultModel=ResultModel.getSuccessInstance();
        try {
        	// 获取userId
        	//user.setId(Integer.parseInt(request.getHeader("userId")));
        	iUserService.editUserInfo(user);
        }catch (Exception e){
            logger.error("编辑用户资料{}",e);
            resultModel=ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }

    /**
     * 关注别的用户
     *
     * @param request
     * @param map
     * @return
     */
    @RequestMapping(value = "/follow", method = RequestMethod.POST)
    public ResultModel follow(HttpServletRequest request, @RequestBody Map map) {
        ResultModel resultModel=ResultModel.getSuccessInstance();
        try {
            String userId = request.getHeader("userId");
            String followId = null;
            if (map.containsKey("followId")) {
                followId = map.get("followId").toString();
            }
            userFollowService.follow(userId, followId);
        }catch (Exception e){
            logger.error("关注别的用户出现异常{}",e);
            resultModel=ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }
    /**
     * 修改头像
     *
     * @param request
     * @param file
     * @return
     */
    @RequestMapping(value = "/updateImage", method = RequestMethod.POST)
    public ResultModel updateImage(HttpServletRequest request,@RequestParam MultipartFile file) {
        ResultModel resultModel=ResultModel.getSuccessInstance();
        try {
            String userId = request.getHeader("userId");
            String url=iUserService.updateImage(userId, file);
            Map<String,Object> map=new HashMap<>();
            map.put("imageUrl",url);
            resultModel.setData(map);
        }catch (Exception e){
            logger.error("修改头像出现异常{}",e);
            resultModel=ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }
    /**
     * 签到
     *
     * @param request
     * @param file
     * @return
     */
    @RequestMapping(value = "/signIn", method = RequestMethod.POST)
    public ResultModel signIn(HttpServletRequest request) {
        ResultModel resultModel=ResultModel.getSuccessInstance();
        try {
            String userId = request.getHeader("userId");
            Map<String,Object> map=iUserService.signIn(userId);
            resultModel.setData(map);
        }catch (Exception e){
            logger.error("签到出现异常{}",e);
            resultModel=ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }
    /**
     * 实名认证
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/realNameAuth", method = RequestMethod.POST)
    public ResultModel realNameAuth(HttpServletRequest request, @RequestBody UserDto userDto) {
        ResultModel resultModel=ResultModel.getSuccessInstance();
        try {
            String userId = request.getHeader("userId");
            userDto.setId(Integer.parseInt(userId));
            iUserService.realNameAuth(userDto);
        }catch (Exception e){
            logger.error("实名认证出现异常{}",e);
            resultModel=ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }
    @Value("${aliyun.oss.REGION_CN_SHANGHAI}")
    private String aliyunOssREGION_CN_SHANGHAI;

    @Value("${aliyun.oss.AccessKeyID}")
    private String aliyunOssAccessKeyID;

    @Value("${aliyun.oss.AccessKeySecret}")
    private String aliyunOssAccessKeySecret;

    @Value("${aliyun.oss.STS_API_VERSION}")
    private String aliyunOssSTS_API_VERSION;

    @Value("${aliyun.oss.RoleArn}")
    private String aliyunOssRoleArn;

    @Value("${aliyun.oss.PolicyFile}")
    private String aliyunOssPolicyFile;

    @Value("${aliyun.oss.TokenExpireTime}")
    private int aliyunOssTokenExpireTime;

    /**
     * 获取临时key
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/getSecret", method = RequestMethod.POST)
    public ResultModel getSecret(@RequestBody Map param) {
        ResultModel resultModel = ResultModel.getSuccessInstance();
        try {
            String roleSessionName=param.get("roleSessionName").toString();
            logger.info("获取临时key roleSessionName={}",roleSessionName);
            // 获取临时授权token
            AssumeRoleResponse assumeRoleResponse = assumeRole(roleSessionName);
            // 构造返回参数
            Map<String, String> map = new HashMap<String, String>();
            // 账号ID
            map.put("accessKeyId", assumeRoleResponse.getCredentials().getAccessKeyId());
            // 密码
            map.put("accessKeySecret", assumeRoleResponse.getCredentials().getAccessKeySecret());
            // token
            map.put("securityToken", assumeRoleResponse.getCredentials().getSecurityToken());
            // 有效时间
            map.put("expiration", assumeRoleResponse.getCredentials().getExpiration());
            map.put("requestID", assumeRoleResponse.getRequestId());
            resultModel.setData(map);
        } catch (Exception e) {
            logger.error("获取临时key 报错{}",e);
            resultModel= ExceptionUtil.getMessageException(e);
        }
        return resultModel;
    }

    public String readJson(String path) {
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        // 返回值,使用StringBuffer
        StringBuffer data = new StringBuffer();
        //
        try {
            inputStream = new ClassPathResource(path).getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);
            // 每次读取文件的缓存
            String temp = null;
            while ((temp = reader.readLine()) != null) {
                data.append(temp);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭文件流
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return data.toString();
    }

    /**
     * 获取阿里云oss sts临时权限
     *
     * @param roleSessionName 临时Token的会话名称
     * @throws ClientException
     * @return 令牌
     */
    public AssumeRoleResponse assumeRole(String roleSessionName) throws ClientException {
        String endpoint = "sts.aliyuncs.com";
        // 创建一个 Aliyun Acs Client, 用于发起 OpenAPI 请求
        // 只有 RAM用户（子账号）才能调用 AssumeRole 接口
        // 阿里云主账号的AccessKeys不能用于发起AssumeRole请求
        // 请首先在RAM控制台创建一个RAM用户，并为这个用户创建AccessKeys
        DefaultProfile.addEndpoint("", "", "Sts", endpoint);
        IClientProfile profile = DefaultProfile.getProfile("", aliyunOssAccessKeyID, aliyunOssAccessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        // 创建一个 AssumeRoleRequest 并设置请求参数
        final AssumeRoleRequest request = new AssumeRoleRequest();
        request.setVersion(aliyunOssSTS_API_VERSION);
        request.setMethod(MethodType.POST);
        // 此处必须为 HTTPS
//        request.setProtocol(ProtocolType.HTTPS);
        // RoleArn 需要在 RAM 控制台上获取
        request.setRoleArn(aliyunOssRoleArn);
        // RoleSessionName 是临时Token的会话名称，自己指定用于标识你的用户，主要用于审计，或者用于区分Token颁发给谁
        // 但是注意RoleSessionName的长度和规则，不要有空格，只能有'-' '_' 字母和数字等字符
        // 具体规则请参考API文档中的格式要求
        request.setRoleSessionName(roleSessionName);
        // 授权策略
        request.setPolicy(readJson(aliyunOssPolicyFile));
        // 设置token时间
        request.setDurationSeconds(aliyunOssTokenExpireTime * 60L);
        // 发起请求，并得到response
        return client.getAcsResponse(request);
    }

}
